<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/21 23:42
 */

namespace module\ai\library\channel\completion;

use module\ai\library\channel\abstract\Completion;

class KimiCompletion extends Completion
{
    protected function rawToData(): void
    {
        $raw = $this->rawData;
        if (!empty($raw['code'])) {
            $code = (int)$raw['code'];
            list($message, $clear) = match ($code) {
                10007 => ['请稍后尝试', true],
                10013 => ['您输入的信息存在违规内容，请重新调整输入内容。', true],
                10014, 10019 => ['对不起，我无法回答你的问题。', true],
                default => [$raw['message'], true],
            };
            $this->error($message, $raw['code'], $clear);
        } elseif (isset($raw['choices'])) {
            $choice = $raw['choices'][0] ?? [];
            $message = $this->stream ? ($choice['delta'] ?? '') : ($choice['message'] ?? '');
            $this->data['message'] = $message ?: ['content' => ''];
            $this->data['status'] = $this->stream ? (empty($choice['finish_reason']) ? 'receiving' : 'finish') : 'finish';
            $this->data['index'] = $choice['index'] ?? 0;
            if (isset($choice['usage'])) {
                $this->data['tokens'] = [
                    'send_tokens'    => $choice['usage']['prompt_tokens'] ?? 0,
                    'receive_tokens' => $choice['usage']['completion_tokens'] ?? 0,
                    'total_tokens'   => $choice['usage']['total_tokens'] ?? 0,
                ];
            }
        }
    }

}